package gitobject;
import repository.Repository;
import zlib.ZLibUtils;

import java.io.*;

//父类设置序列化接口，子类继承则不需要再继续设置接口
public class GitObject implements Serializable{

    protected String fmt;                  //type of object
    protected String key;                  //key of object
    protected String mode;                 //mode of object
    protected static String path = Repository.getGitDir() + File.separator + "objects";          //absolute path of objects
    protected String value;                //value of object

    public String getFmt(){
        return fmt;
    }
    public String getKey() { return key; }
    public String getMode(){
        return mode;
    }
    public String getPath() {
        return path;
    }
    public String getValue(){
        return value;
    }


    public GitObject(){}
    /**
     * Get the value(content) of file
     * @param file
     * @return String
     * @throws IOException
     * 获取文件内容
     */
    public static String getValue(File file) throws IOException {
        /* Todo: Add your code here
        *   You should delete the return statement below before coding.  */
       try{
        //逐行获取文件的内容
        String value = "";
        BufferedReader bf = new BufferedReader(new FileReader(file));
        String sendStr;
        while((sendStr = bf.readLine()) != null){
            value += sendStr;
        }
        return value;
        }catch(Exception e){
            e.printStackTrace();
            return null;
        }
    }
    /**
     * Todo: Serialize the object to the local repository.
     * @throws Exception
     */
    public void writeObject() throws Exception{
        /**
         * Add your code here.
         */
        //序列化方法
        FileOutputStream file = new FileOutputStream("D:/tes/.jit/objects" + File.separator +this.getKey());
        ObjectOutputStream oos = new ObjectOutputStream(file);
        System.out.println(this);
        oos.writeObject(this);
        oos.close();
    }

    /**
     * Todo: Serialize the object and compress with zlib.
     * @throws Exception
     */
    public void compressWrite() throws Exception{
        /**
         * Add your code here.
         */
        byte[] bt = this.value.getBytes();
        byte[] cb = ZLibUtils.compress(bt);
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(path +File.separator+ this.key));
        ZLibUtils.compress(cb,oos);
    }

}
